package com.jxnu.duewang.zmly.zouZhen.adapter.two;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v4.util.Pair;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Project Zmly
 * Author Duewang
 * Time 2016/12/15 0015
 */

public class CommonRecycleAdapter<D> extends RecyclerView.Adapter<CommonRecycleAdapter.ViewHolder> {

    private Context mContext;
    private List<D> mList;
    private Map<Class<?>,Pair<Integer,Integer>> mMap;

    public CommonRecycleAdapter(Context context,List<D> list,Map<Class<?>,Pair<Integer,Integer>> map){
        mContext=context;
        mList=list;
        mMap=map;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(DataBindingUtil.inflate(LayoutInflater.from(mContext),viewType,parent,false));
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        D d = mList.get(position);
        Pair<Integer,Integer> pair=mMap.get(d.getClass());
        if(pair.second!=0){
            holder.mBinding.setVariable(pair.second,d);
        }
    }

    @Override
    public int getItemCount() {
        int ret=0;
        if (mList != null) {
            ret=mList.size();
        }
        return ret;
    }

    @Override
    public int getItemViewType(int position) {
        return mMap.get(mList.get(position).getClass()).first;
    }

    public void add(D d){
        add(mList.size(),d);
    }

    public void add(int position,D d){
        if (d != null) {
            mList.add(position,d);
            notifyItemInserted(position);
        }
    }

    public void remove(D d){
        int index = mList.indexOf(d);
        remove(index);
    }

    public void remove(int position){
        mList.remove(position);
        notifyItemRemoved(position);
    }

    public void addAll(Collection<? extends D> collection){
        addAll(mList.size(),collection);
    }

    public void addAll(int position,Collection<? extends D> collection){
        if (collection != null) {
            mList.addAll(position,collection);
            notifyItemRangeInserted(position,collection.size());
        }
    }

    static class ViewHolder extends RecyclerView.ViewHolder{

        private ViewDataBinding mBinding;

        ViewHolder(ViewDataBinding binding){
            super(binding.getRoot());
            mBinding=binding;
        }

    }
}
